<script setup lang="ts">
import { ref, watch } from 'vue';

import { message } from 'ant-design-vue';
import dayjs from 'dayjs';

interface UploadedImage {
  id: string;
  name: string;
  url: string;
  uploadTime: string;
  type: 'upload';
}

interface Props {
  visible: boolean;
}

interface Emits {
  (e: 'update:visible',visible: boolean): void;
  (e: 'success',images: UploadedImage[]): void
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

// 响应式数据
const fileList = ref<any[]>([]);
const uploadedImages = ref<UploadedImage[]>([]);

// 方法
const beforeUpload = (file: File) => {
  const isImage = file.type.startsWith('image/');
  if (!isImage) {
    message.error('只能上传图片文件！');
    return false;
  }

  const isLt10M = file.size / 1024 / 1024 < 10;
  if (!isLt10M) {
    message.error('图片大小不能超过 10MB！');
    return false;
  }

  return false; // 阻止自动上传
};

const handleChange = (info: any) => {
  const { fileList: newFileList } = info;
  fileList.value = newFileList;

  // 处理新上传的文件
  newFileList.forEach((file: any) => {
    if (file.status === 'done' || file.originFileObj) {
      const reader = new FileReader();
      reader.addEventListener('load', (e) => {
        const uploadedImage: UploadedImage = {
          id: Date.now().toString() + Math.random().toString(36).slice(2),
          name: file.name || `X光片_${dayjs().format('YYYYMMDD_HHmmss')}`,
          url: e.target?.result as string,
          uploadTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
          type: 'upload',
        };
        uploadedImages.value.push(uploadedImage);
      });
      reader.readAsDataURL(file.originFileObj || file);
    }
  });
};

const removeImage = (index: number) => {
  uploadedImages.value.splice(index, 1);
  // 同时从文件列表中移除
  fileList.value.splice(index, 1);
};

const handleConfirm = () => {
  if (uploadedImages.value.length === 0) {
    message.warning('请先上传图片');
    return;
  }

  emit('success', uploadedImages.value);
  handleCancel();
};

const handleCancel = () => {
  emit('update:visible', false);
  // 重置状态
  fileList.value = [];
  uploadedImages.value = [];
};

// 监听模态框显示状态
watch(
  () => props.visible,
  (visible) => {
    if (!visible) {
      // 重置状态
      fileList.value = [];
      uploadedImages.value = [];
    }
  },
);
</script>

<template>
  <a-modal
    :visible="visible"
    title="上传X光片"
    width="600px"
    @cancel="handleCancel"
    :footer="null"
  >
    <div class="image-upload-modal">
      <!-- 上传区域 -->
      <div class="upload-area">
        <a-upload-dragger
          v-model:file-list="fileList"
          :before-upload="beforeUpload"
          :multiple="true"
          accept="image/*"
          @change="handleChange"
        >
          <p class="ant-upload-drag-icon">📷</p>
          <p class="ant-upload-text">点击或拖拽文件到此区域上传</p>
          <p class="ant-upload-hint">
            支持单个或批量上传，仅支持 jpg/png 格式图片
          </p>
        </a-upload-dragger>
      </div>

      <!-- 已上传图片预览 -->
      <div v-if="uploadedImages.length > 0" class="preview-section">
        <h4>已上传图片</h4>
        <div class="preview-grid">
          <div
            v-for="(image, index) in uploadedImages"
            :key="index"
            class="preview-item"
          >
            <div class="preview-container">
              <img :src="image.url" :alt="image.name" />
              <div class="preview-overlay">
                <a-button
                  type="text"
                  size="small"
                  danger
                  @click="removeImage(index)"
                >
                  ×
                </a-button>
              </div>
            </div>
            <div class="preview-info">
              <a-input
                v-model:value="image.name"
                size="small"
                placeholder="图片名称"
              />
            </div>
          </div>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="modal-actions">
        <a-button @click="handleCancel">取消</a-button>
        <a-button
          type="primary"
          @click="handleConfirm"
          :disabled="uploadedImages.length === 0"
        >
          确认上传 ({{ uploadedImages.length }})
        </a-button>
      </div>
    </div>
  </a-modal>
</template>

<style scoped>
.image-upload-modal {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.upload-area {
  padding: 16px;
  border: 1px solid #e8e8e8;
  border-radius: 6px;
}

.preview-section {
  padding: 16px;
  border: 1px solid #e8e8e8;
  border-radius: 6px;
}

.preview-section h4 {
  margin: 0 0 16px;
  font-size: 14px;
  color: #333;
}

.preview-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 16px;
}

.preview-item {
  overflow: hidden;
  border: 1px solid #e8e8e8;
  border-radius: 6px;
}

.preview-container {
  position: relative;
  height: 120px;
  overflow: hidden;
}

.preview-container img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.preview-overlay {
  position: absolute;
  top: 4px;
  right: 4px;
  opacity: 0;
  transition: opacity 0.3s;
}

.preview-container:hover .preview-overlay {
  opacity: 1;
}

.preview-info {
  padding: 8px;
}

.modal-actions {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
  padding-top: 16px;
  border-top: 1px solid #e8e8e8;
}

:deep(.ant-upload-drag-icon) {
  margin-bottom: 16px;
  font-size: 48px;
}

:deep(.ant-upload-text) {
  margin-bottom: 8px;
  font-size: 16px;
  color: #333;
}

:deep(.ant-upload-hint) {
  font-size: 14px;
  color: #666;
}
</style>
